﻿using zijian666.Abstractions;
using zijian666.Convertor.Base;
using zijian666.Core;
using zijian666.ConvertExtensions;

namespace zijian666.Convertor;
/// <summary>
/// <seealso cref="DirectoryInfo"/> 转换器
/// </summary>
public class FileInfoConvertor :
    AllowNullConvertor<FileInfo>,
    IFrom<string, FileInfo>,
    IFrom<Uri, FileInfo>
{
    /// <inheritdoc />
    public ConvertResult<FileInfo> From(IConvertContext context, string input)
    {
        if (string.IsNullOrWhiteSpace(input))
        {
            return default;
        }
        input = input.Trim();
        if (input.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
        {
            input = input.Substring(7);
            return new FileInfo(input);
        }
        if (Uri.TryCreate(input, UriKind.RelativeOrAbsolute, out var uri))
        {
            return From(context, uri);
        }
        return context.ConvertFail(this, input);
    }
    /// <inheritdoc />
    public ConvertResult<FileInfo> From(IConvertContext context, Uri input)
    {
        if (input is null)
        {
            return default;
        }
        if (!input.IsAbsoluteUri)
        {
            var s = input.ToString();
            if (s[0] is not '.')
            {
                return context.ConvertFail(this, s);
            }
            if (s.Length is 1 || s[1] is '/' or '\\')
            {
                return new FileInfo(s);
            }

            if (s[1] is not '.')
            {
                return context.ConvertFail(this, s);
            }
            if (s.Length is 2 || s[2] is '/' or '\\')
            {
                return new FileInfo(s);
            }

            return context.ConvertFail(this, s);
        }
        else if (input.IsFile)
        {
            return new FileInfo(input.LocalPath);
        }
        return context.ConvertFail(this, input.ToString());
    }
}
